"""
从 book_info.txt 文件中读取数据
"""

from book_def import BookInfo


class FileOperation:

    # 传入文件路径
    def __init__(self, path):
        self.path = path

    # 读取文件内容
    def read_file(self) -> list[BookInfo]:
        try:
            f = open(self.path, "r", encoding="UTF-8")
            book_info_list: list[BookInfo] = []

            for line in f.readlines():
                line = line.strip()
                data_list = line.split(",")
                book_info = BookInfo(data_list[0], data_list[1], float(data_list[2]))
                book_info_list.append(book_info)
            f.close()
            return book_info_list
        except FileNotFoundError:
            print(f"文件不存在！")

    # 追加写文件
    def write_file(self, book_info: BookInfo):
        f = open(self.path, "a", encoding="UTF-8")
        line = f"{book_info.book},{book_info.author},{book_info.price}"
        f.write(line)
        f.write("\n")
        f.close()

    # 清空文件
    def clean_file(self):
        f = open(self.path, "w", encoding="UTF-8")
        f.close()


if __name__ == '__main__':
    fo = FileOperation("../../doc/book_info.txt")
    fo.clean_file()
